package com.cheung.leetcode.arr;

import  org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.arr
 * @Author :  cheungming
 * @CreateTime : 2024-07-14 21:08:15
 * @Description : 80. 删除排序数组中的重复项 II
 * @Version : 1.0
 */
public class Code80Test {

    public int removeDuplicates(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        int len = nums.length;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (map.getOrDefault(nums[i], 0) < 2) {
                map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
            } else {
                len--;
                // 当前元素之后的元素全部向前移动一位
                for (int j = i; j < len; j++) {
                    nums[j] = nums[j + 1];
                }
            }
        }
        return len;
    }

    @Test
    public void test1() {
        int[] nums = {1, 1, 1, 2, 2, 3};
        assert removeDuplicates(nums) == 5;
        assert nums[0] == 1 && nums[1] == 1 && nums[2] == 2 && nums[3] == 2 && nums[4] == 3;
    }
}
